package com.tgpms.web.tongfei.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.tgpms.common.MultipartFileToFile;
import com.tgpms.common.Result;
import com.tgpms.web.tongfei.TongfeiController;
import com.tgpms.web.tongfei.entity.InLog;
import com.tgpms.web.tongfei.pojo.Log;
import com.tgpms.web.tongfei.pojo.Newpsnode;
import com.tgpms.web.tongfei.pojo.R;
import com.tgpms.web.tongfei.service.IInLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 控制层
 * </p>
 *
 * @author jl
 * @since 2020-11-25
 */
@Api(value = "InLogController", tags = "施工日志记录相关接口")
@RestController
@RequestMapping("/tongfei")
public class InLogController {
    @Value("${tongfei.path}")
    private String host;
    @Resource
    private RedisTemplate<String, Object> redis;
    @Autowired
    private IInLogService inLogService;

    /**
     * 新增施工日志记录
     */
    @ApiOperation(value = "新增施工日志记录", notes = "新增施工日志记录", httpMethod = "POST")
    @PostMapping("/tofly-sxgk/log")
    public Result addLog(@RequestParam(value = "log") String jsonString, HttpServletRequest request) {
        InLog inLog = JSON.parseObject(jsonString, InLog.class);
        List<MultipartFile> files = new ArrayList<>();
        // 获取文件集合
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtil.isNotEmpty(fileMap)) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取单个文件
                MultipartFile mf = entity.getValue();
                files.add(mf);
            }
        }

        // 临时文件,最后要删除
        List<File> images = new ArrayList<>();
        try {
            // 发送给同飞的参数
            Map<String, Object> paramMap = new HashMap<>();
            // 图片集合
            if (CollectionUtil.isNotEmpty(files)) {
                for (int i = 0; i < files.size(); i++) {
                    File image = MultipartFileToFile.multipartFileToFile(files.get(i));
                    paramMap.put(files.get(i).getOriginalFilename(), image);
                    images.add(image);
                }
            }
            // 调用同飞修改接口
            paramMap.put("notes", inLog.getNotes());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            paramMap.put("quantities", sdf.format(inLog.getQuantities()));
            String token = request.getHeader("tfToken");
            String body = HttpRequest.post(host + "/tofly-sxgk/log")
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header(Header.CONTENT_TYPE, "multipart/form-data")
                    .form(paramMap)
                    .execute().body();
            R r = JSON.parseObject(body, R.class);
            if (r.getCode() == 1) {
                // 本地新增
                String json = JSON.toJSONString(r.getResult());
                Log data = JSON.parseObject(json, Log.class);
                inLog.setRowstamp(String.valueOf(data.getId()));
                inLog.setInsertUser(this.getUsername(token));
                return inLogService.addInLog(inLog);
            } else {
                return TongfeiController.tongfeiResponseToResult(r);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        } finally {
            MultipartFileToFile.delteTempFile(images);
        }
    }

    /**
     * 修改施工日志记录
     */
    @ApiOperation(value = "修改施工日志记录", notes = "修改施工日志记录", httpMethod = "POST")
    @PostMapping("/tofly-sxgk/updateLog")
    public Result updateLog(@RequestParam(value = "log") String jsonString, HttpServletRequest request) {
        Log log = JSON.parseObject(jsonString, Log.class);
        List<MultipartFile> files = new ArrayList<>();
        // 获取文件集合
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtil.isNotEmpty(fileMap)) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取单个文件
                MultipartFile mf = entity.getValue();
                files.add(mf);
            }
        }

        // 临时文件,最后要删除
        List<File> images = new ArrayList<>();
        try {
            // 发送给同飞的参数
            Map<String, Object> paramMap = new HashMap<>();
            // 图片集合
            if (CollectionUtil.isNotEmpty(files)) {
                for (int i = 0; i < files.size(); i++) {
                    File image = MultipartFileToFile.multipartFileToFile(files.get(i));
                    paramMap.put(files.get(i).getOriginalFilename(), image);
                    images.add(image);
                }
            }
            // 调用同飞修改接口
            paramMap.put("id", log.getId());
            paramMap.put("notes", log.getNotes());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            paramMap.put("quantities", sdf.format(log.getQuantities()));
            String token = request.getHeader("tfToken");
            String body = HttpRequest.put(host + "/tofly-sxgk/log")
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .body(JSON.toJSONString(paramMap))
                    .execute().body();
            R r = JSON.parseObject(body, R.class);
            if (r.getCode() == 1) {
                // 本地修改
                InLog inLog = inLogService.getInLogByRowstamp(String.valueOf(log.getId()));
                BeanUtil.copyProperties(log, inLog, "id");
                inLog.setModifyUser(this.getUsername(token));
                inLog.setModifyDate(new Date());
                return inLogService.updateInLog(inLog);
            } else {
                return TongfeiController.tongfeiResponseToResult(r);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        } finally {
            MultipartFileToFile.delteTempFile(images);
        }
    }

    /**
     * 分页查询施工日志记录
     */
    @ApiOperation(value = "分页查询施工日志记录", notes = "分页查询施工日志记录", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/log/page")
    public Result page(Newpsnode newpsnode, HttpServletRequest request) {
        Map<String, Object> paramMap = BeanUtil.beanToMap(newpsnode, false, true);
        paramMap.put("orders[0].column", "create_time");
        paramMap.put("orders[0].asc", false);
        return TongfeiController.normalGet("/tofly-sxgk/log/page", paramMap, request);
    }

    private String getUsername(String token) {
        return (String) redis.opsForValue().get(token);
    }
}
